package com.pactera.miyuangroup.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.pactera.miyuangroup.common.Constants;
import com.pactera.miyuangroup.common.RedisOperation;
import com.pactera.miyuangroup.config.CommonConfig;
import com.pactera.miyuangroup.db.entity.GoodsInfo;
import com.pactera.miyuangroup.db.entity.VendorInfo;
import com.pactera.miyuangroup.db.entity.VendorPassageway;
import com.pactera.miyuangroup.db.mapper.VendorPassagewayMapper;
import com.pactera.miyuangroup.service.GoodsInfoService;
import com.pactera.miyuangroup.service.MiyuanDataService;
import com.pactera.miyuangroup.service.VendorInfoService;
import com.pactera.miyuangroup.service.VendorPassagewayService;
import com.pactera.miyuangroup.util.ReadExcelUtils;
import com.pactera.miyuangroup.vo.response.miyuan.MiYuanModel;
import com.pactera.miyuangroup.vo.response.miyuan.VendorPassagewayIncrementInfo;
import com.pactera.miyuangroup.vo.response.miyuan.VendorPassagewayInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 售货机货道 服务实现类
 * </p>
 *
 * @author WangWu
 * @since 2018-04-13
 */
@Service
@Slf4j
public class VendorPassagewayServiceImp extends ServiceImpl<VendorPassagewayMapper, VendorPassageway> implements VendorPassagewayService {
    @Autowired
    private CommonConfig config;
    @Autowired
    private RedisOperation redis;

    @Autowired
    private MiyuanDataService miyuanDataService;

    @Autowired
    private VendorInfoService vendorInfoService;

    @Autowired
    private GoodsInfoService goodsInfoService;
    //新增集合
    private List<VendorPassageway> inst = new ArrayList<>();

    /**
     * 同步售货机货道信息
     *
     * @return
     */
    @Override
    public boolean syncMiyuanVendorPassagewayInfo() {
        //miYuanVendorPassagewayInfo();
        //开始更新
        boolean flg = redis.get(Constants.REDIS_MIYUAN_VENDOR_PASSAGEWAY_INFO_SYNC, Boolean.class, Boolean.TRUE);
        if (!flg) {
            return false;
        }
        //使用多线程
        miyuanDataService.executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    redis.set(Constants.REDIS_MIYUAN_VENDOR_PASSAGEWAY_INFO_SYNC, Boolean.FALSE);
                    //增量
                    miYuanVendorPassagewayIncrementInfo(new Date());
                    redis.set(Constants.REDIS_MIYUAN_VENDOR_PASSAGEWAY_INFO_SYNC, Boolean.TRUE);
                } catch (Exception e) {
                    log.error("同步米源售货机货道信息发生异常", e);
                    redis.set(Constants.REDIS_MIYUAN_VENDOR_PASSAGEWAY_INFO_SYNC, Boolean.TRUE);
                }
            }
        });
        return true;
    }

    @Override
    public void syncMiyuanVendorPassagewaySchedulerInfo() {
        try {
            //查询是否有历史数据
            int count = selectCount(null);
            //增量（同步上一天的）
            miYuanVendorPassagewayIncrementInfo(new com.pactera.miyuangroup.util.Date().addDays(-1));
        } catch (Exception e) {
            log.error("定时任务同步米源售货机货道信息发生异常", e);
        }
    }


    @Override
    public void excelImport() {
        //使用多线程
        miyuanDataService.executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    log.info("开始读取excel，路径：{}", config.getExcelInitializationPath());
                    ReadExcelUtils read = new ReadExcelUtils(config.getExcelInitializationPath());
                    List<List<String>> r = read.getList();
                    log.info("excel读取成功，共{}行", r.size());
                    log.info("开始-循环入库");
                    for (List<String> s : r) {
                        VendorPassagewayIncrementInfo vendorPassagewayIncrementInfo = new VendorPassagewayIncrementInfo();
                        vendorPassagewayIncrementInfo.setNumber(s.get(0));
                        vendorPassagewayIncrementInfo.setGoodsId(s.get(1));
                        vendorPassagewayIncrementInfo.setMaxNumber(s.get(2));
                        vendorPassagewayIncrementInfo.setPassagewayNumber(s.get(3));
                        excelVendorPassagewayIncrementInfo(vendorPassagewayIncrementInfo);
                    }
                    log.info("验证是否剩余货道");
                    if (inst.size() > 0) {
                        log.info("剩余货道数:【{}】", inst.size());
                        insertBatch(inst, inst.size());
                    } else {
                        log.info("无剩余货道");
                    }
                    log.info("结束-循环入库");
                } catch (Exception e) {
                    log.error("导入货道信息错误：{}", e.getMessage());
                }
            }
        });
    }

    @Override
    public void syncMiyuanVendorPassagewaySchedulerInfo(Date d) {
        miYuanVendorPassagewayIncrementInfo(d);
    }

    /*******************货道同步*************************/
    /**
     * 同步米源数据
     */
    private void miYuanVendorPassagewayInfo() {
        log.info("同步米源售货机货道信息开始");
        int p = 1;
        ExecutorService huodao = Executors.newFixedThreadPool(config.getVendorPassagewayThreadPool());
        while (true) {
            //查询所有售货机信息
            Page<VendorInfo> vendorInfos = vendorInfoService.selectPage(new Page<>(p, 200));
            for (VendorInfo vendorInfo : vendorInfos.getRecords()) {
                //使用多线程
                huodao.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            vendorPassageway(vendorInfo);
                        } catch (Exception e) {
                            log.error("同步米源售货机货道信息发生异常", e);
                        }
                    }
                });
            }
            if (!vendorInfos.hasNext()) {
                log.info("同步米源售货机货道信息结束");
                break;
            }
            p++;
        }
        huodao.shutdown();
    }

    private void vendorPassageway(VendorInfo vendorInfo) {
        MiYuanModel<List<VendorPassagewayInfo>> miyuan = miyuanDataService.getVendorPassagewayInfo(vendorInfo.getNumber());
        //查询是否成功
        if (!miyuan.isSuccess()) {
            return;
        }
        //查询是否成功
        if (null == miyuan.getData() || miyuan.getData().size() <= 0) {
            return;
        }
        //新增售货机集合
        List<VendorPassageway> instInfos = new ArrayList<>();
        //删除原有所有货道
        EntityWrapper<VendorPassageway> ew = new EntityWrapper<>();
        ew.eq("vendor_id", vendorInfo.getId());
        delete(ew);
        //循环数据入库
        for (VendorPassagewayInfo vendorPassagewayInfo : miyuan.getData()) {
            VendorPassageway info = new VendorPassageway();
            info.setVendorId(vendorInfo.getId());
            info.setPassagewayNumber(Integer.parseInt(vendorPassagewayInfo.getPassagewayNumber()));

            //根据商品编号查询商品信息
            EntityWrapper<GoodsInfo> goodsInfoEntityWrapper = new EntityWrapper<>();
            goodsInfoEntityWrapper.eq("number", vendorPassagewayInfo.getGoodsId());
            GoodsInfo goodsInfo = goodsInfoService.selectOne(goodsInfoEntityWrapper);
            if (null != goodsInfo) {
                //关联商品和货道
                info.setGoodsId(goodsInfo.getId());
            }
            info.setMaxNumber(Integer.parseInt(vendorPassagewayInfo.getMaxNumber()));
            instInfos.add(info);
        }

        //新增
        if (instInfos.size() > 0) {
            insertBatch(instInfos, instInfos.size());
        }
    }
    /********************************************/

    /*******************货道增量同步*************************/
    private void miYuanVendorPassagewayIncrementInfo(Date d) {
        MiYuanModel<List<VendorPassagewayIncrementInfo>> miyuan = miyuanDataService.getVendorPassagewayIncrementInfo(d);
        //查询是否成功
        if (!miyuan.isSuccess()) {
            return;
        }
        //查询是否成功
        if (null == miyuan.getData() || miyuan.getData().size() <= 0) {
            return;
        }

        //新增集合
        List<VendorPassageway> instInfos = new ArrayList<>();

        //修改集合
        List<VendorPassageway> upInfos = new ArrayList<>();

        int dSize = miyuan.getData().size();
        //循环数据入库
        for (VendorPassagewayIncrementInfo vendorPassagewayIncrementInfo : miyuan.getData()) {

            //查询售货机ID
            EntityWrapper<VendorInfo> vendorInfoEntityWrapper = new EntityWrapper<>();
            vendorInfoEntityWrapper.eq("number", vendorPassagewayIncrementInfo.getNumber());
            VendorInfo vendorInfo = vendorInfoService.selectOne(vendorInfoEntityWrapper);
            if (null == vendorInfo) {
                log.info("货道增量同步，售货机编号【{}】未查询到信息", vendorPassagewayIncrementInfo.getNumber());
                continue;
            }
            //查询货道
            EntityWrapper<VendorPassageway> ew = new EntityWrapper<>();
            ew.eq("vendor_id", vendorInfo.getId());
            ew.eq("passageway_number", vendorPassagewayIncrementInfo.getPassagewayNumber());
            VendorPassageway info = selectOne(ew);
            //没有记录
            if (null == info) {
                log.info("货道增量同步(新增)，未查询到对应的货道信息【售货机ID：{},货道编号：{}】", vendorInfo.getId(), vendorPassagewayIncrementInfo.getPassagewayNumber());
                info = new VendorPassageway();
                info.setVendorId(vendorInfo.getId());
                info.setPassagewayNumber(Integer.parseInt(vendorPassagewayIncrementInfo.getPassagewayNumber()));

                //根据商品编号查询商品信息
                EntityWrapper<GoodsInfo> goodsInfoEntityWrapper = new EntityWrapper<>();
                goodsInfoEntityWrapper.eq("number", vendorPassagewayIncrementInfo.getGoodsId());
                GoodsInfo goodsInfo = null;
                if (StringUtils.isNotBlank(vendorPassagewayIncrementInfo.getGoodsId())) {
                    goodsInfo = goodsInfoService.selectOne(goodsInfoEntityWrapper);
                    if (null != goodsInfo) {
                        //关联商品和货道
                        info.setGoodsId(goodsInfo.getId());
                    } else {
                        log.info("货道增量同步(新增)，商品编号【{}】未查询到商品信息", vendorPassagewayIncrementInfo.getGoodsId());
                    }
                } else {
                    log.info("货道增量同步(新增)，【售货机ID：{},货道编号：{}】没有商品编号", vendorInfo.getId(), vendorPassagewayIncrementInfo.getPassagewayNumber());
                }
                info.setMaxNumber(Integer.parseInt(vendorPassagewayIncrementInfo.getMaxNumber()));
                instInfos.add(info);
            } else {
                info.setVendorId(vendorInfo.getId());
                info.setPassagewayNumber(Integer.parseInt(vendorPassagewayIncrementInfo.getPassagewayNumber()));

                //根据商品编号查询商品信息
                EntityWrapper<GoodsInfo> goodsInfoEntityWrapper = new EntityWrapper<>();
                goodsInfoEntityWrapper.eq("number", vendorPassagewayIncrementInfo.getGoodsId());
                GoodsInfo goodsInfo = null;
                if (StringUtils.isNotBlank(vendorPassagewayIncrementInfo.getGoodsId())) {
                    goodsInfo = goodsInfoService.selectOne(goodsInfoEntityWrapper);
                    if (null != goodsInfo) {
                        //关联商品和货道
                        info.setGoodsId(goodsInfo.getId());
                    } else {
                        log.info("货道增量同步(修改)，商品编号【{}】未查询到商品信息", vendorPassagewayIncrementInfo.getGoodsId());
                    }
                } else {
                    log.info("货道增量同步(修改)，【售货机ID：{},货道编号：{}】没有商品编号", vendorInfo.getId(), vendorPassagewayIncrementInfo.getPassagewayNumber());
                }
                info.setMaxNumber(Integer.parseInt(vendorPassagewayIncrementInfo.getMaxNumber()));
                upInfos.add(info);
            }

            int iSize = instInfos.size();
            int uSize = upInfos.size();
            if (iSize > 0 && iSize == 200) {
                insertBatch(instInfos, iSize);
                instInfos = new ArrayList<>();
            }
            if (uSize > 0 && uSize == 200) {
                updateBatchById(upInfos, uSize);
                upInfos = new ArrayList<>();
            }

        }
        //新增
        if (instInfos.size() > 0) {
            insertBatch(instInfos, instInfos.size());
        }
        //修改
        if (upInfos.size() > 0) {
            updateBatchById(upInfos, instInfos.size());
        }
    }

    /********************************************/


    private void excelVendorPassagewayIncrementInfo(VendorPassagewayIncrementInfo vendorPassagewayIncrementInfo) {
        //查询售货机ID
        EntityWrapper<VendorInfo> vendorInfoEntityWrapper = new EntityWrapper<>();
        vendorInfoEntityWrapper.eq("number", vendorPassagewayIncrementInfo.getNumber());
        VendorInfo vendorInfo = vendorInfoService.selectOne(vendorInfoEntityWrapper);
        if (null == vendorInfo) {
            log.info("售货机编号：{} 未查询到售货机", vendorPassagewayIncrementInfo.getNumber());
            return;
        }
        VendorPassageway info = new VendorPassageway();
        info.setVendorId(vendorInfo.getId());
        info.setPassagewayNumber(Integer.parseInt(vendorPassagewayIncrementInfo.getPassagewayNumber()));
        //根据商品编号查询商品信息
        EntityWrapper<GoodsInfo> goodsInfoEntityWrapper = new EntityWrapper<>();
        goodsInfoEntityWrapper.eq("number", vendorPassagewayIncrementInfo.getGoodsId());
        GoodsInfo goodsInfo = goodsInfoService.selectOne(goodsInfoEntityWrapper);
        if (null != goodsInfo) {
            //关联商品和货道
            info.setGoodsId(goodsInfo.getId());
        } else {
            log.info("商品编号：{} 未查询到商品信息", vendorPassagewayIncrementInfo.getGoodsId());
        }
        info.setMaxNumber(Integer.parseInt(vendorPassagewayIncrementInfo.getMaxNumber()));
        inst.add(info);
        int i = inst.size();
        if (i > 0 && i == 1000) {
            log.info("1000条数据开始入库");
            boolean flg = insertBatch(inst, i);
            if (flg) {
                log.info("1000条数据入库成功");
                inst = new ArrayList<>();
            }
            log.info("1000条数据入库结束");
        }
    }

}
